package cn.chencq.gdt.banner;

import java.net.Proxy;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.chencq.gdt.common.Constants;
import cn.chencq.gdt.utils.HttpUtils;
import cn.chencq.gdt.utils.Utils;
import cn.chencq.gdt.vo.BanerAd;
import cn.chencq.gdt.vo.Gdt;
import cn.chencq.gdt.vo.Mobile;
import cn.chencq.gdt.vo.ProxyIp;

import com.alibaba.fastjson.JSONObject;

public class GdtBaner {

	private static final Logger logger = LoggerFactory.getLogger(GdtBaner.class);

	/**
	 * 请求banner广告
	 * 
	 * @param gdt
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static BanerAd queryAd(String rid, Gdt gdt, ProxyIp proxyIp, Mobile mobile) {
		StringBuilder sb = new StringBuilder();
		sb.append("adposcount=").append(1).append("&");
		sb.append("count=").append(1).append("&");
		sb.append("posid=").append(gdt.getPosid()).append("&");// 广告位posid
		
		int dpi = mobile.getDpi();//手机DPI
		int posw = 640;
		int posh = 100;
		if(dpi<160){//普通
			posw = 240;
			posh = 38;
		}else if(dpi>=160 && dpi<240){//标清
			posw = 320;
			posh = 50;
		}else if(dpi>=240 && dpi<320){//高清
			posw = 480;
			posh = 75;
		}else if(dpi>=320){//超高清
			posw = 640;
			posh = 100;
		}
		
		sb.append("posw=").append(posw).append("&");// 广告位宽
		sb.append("posh=").append(posh).append("&");// 广告位高
		sb.append("charset=").append("utf8").append("&");
		sb.append("datafmt=").append("json").append("&");
		sb.append("remoteip=").append(proxyIp.getIp()).append("&");// 代理ip

		JSONObject ext = new JSONObject();
		JSONObject req = new JSONObject();
		req.put("apiver", "1.4");
		req.put("appid", gdt.getAppid());// appid

		String c_os = gdt.getC_os();// 操作系统
		req.put("c_os", c_os);
		
		String c_osver = mobile.getOs_ver();// 操作系统
		req.put("c_osver", c_osver);

		int muidtype = gdt.getMuidtype();// 移动终端标识类型
		req.put("muidtype", muidtype);

		String muid = getMuid(muidtype);// idfa或mac经过md5加密
		req.put("muid", muid);

		req.put("c_device", mobile.getBrand());// 手机品牌，IOS默认Apple

		req.put("c_pkgname", gdt.getC_packname());// APP包名

		req.put("posttype", gdt.getPosttype());// 广告类型1:baner,2:插屏,3:应用墙,4:开屏,5:feed,8:原生

		req.put("conn", 1);// 联网方式1：WiFi,2:2g.3:3g,4:4g
		req.put("carrier", 1);// 运营商1:移动2:联通3:电信

		req.put("c_w", mobile.getW());// 屏幕宽
		req.put("c_h", mobile.getH());// 屏幕高

		ext.put("req", req);
		sb.append("ext=").append(URLEncoder.encode(ext.toString()));

		String url = Constants.QUERY_AD_URL + "?" + sb.toString();
		Proxy proxy = null;
		String resp = HttpUtils.getResponse(url, proxy, mobile.getUserAgent());

		logger.info("rid:{},muid:{},url:{},resp:{}", rid, muid, url, resp);

		JSONObject json = JSONObject.parseObject(resp);
		int ret = json.getIntValue("ret");
		if (ret == 0) {// 请求广告成功
			BanerAd baner = new BanerAd();
			JSONObject data = json.getJSONObject("data");
			JSONObject adPos = data.getJSONObject(gdt.getPosid());
			JSONObject ad = adPos.getJSONArray("list").getJSONObject(0);

			baner.setActtype(ad.getIntValue("acttype"));
			baner.setBtn_render(ad.getIntValue("btn_render"));
			baner.setCrt_type(ad.getIntValue("crt_type"));
			baner.setDesc(ad.getString("desc"));
			baner.setImg(ad.getString("img"));
			baner.setImg2(ad.getString("img2"));
			baner.setRl(ad.getString("rl"));
			baner.setTargetid(ad.getString("targetid"));
			baner.setTxt(ad.getString("txt"));
			baner.setViewid(ad.getString("viewid"));
			return baner;
		} else {
			return null;
		}
	}

	private static String getMuid(int muidtype) {
		String muid = null;
		switch (muidtype) {
		case 1:
			break;
		case 2:// idfa
			String idfa = Utils.getIdfa();
			muid = Utils.md5(idfa);
			break;
		case 3:// mac
			String mac = Utils.getMAC().replaceAll(":", "").toLowerCase();
			muid = Utils.md5(mac);
			break;
		default:
			break;
		}
		return muid;
	}

	/**
	 * 曝光
	 * 
	 * @param ad
	 * @param proxyIp
	 * @return
	 */
	public static boolean display(String rid, BanerAd ad, ProxyIp proxyIp, Mobile mobile) {
		boolean ret = false;
		Proxy proxy = Utils.setProxy(proxyIp.getIp(), proxyIp.getPort());
		String img = ad.getImg();
		String img2 = ad.getImg2();

		if (img != null && img.length() > 0) {
			HttpUtils.getResponeCode(img, proxy, mobile.getUserAgent());
		}

		if (img2 != null && img2.length() > 0) {
			HttpUtils.getResponeCode(img2, proxy, mobile.getUserAgent());
		}

		StringBuilder sb = new StringBuilder();
		sb.append("count=").append(1).append("&");// 曝光数量1
		sb.append("viewid0=").append(ad.getViewid());

		String url = Constants.DISPLAY_AD_URL + "?" + sb.toString();

		int code = HttpUtils.getResponeCode(url, proxy, mobile.getUserAgent());
		if (code == 204) {
			ret = true;
		}
		logger.info("rid:{},proxy:{},url:{},code:{},display:{}", rid, proxyIp.toString(), url, code, ret);
		return ret;
	}

	/**
	 * 点击
	 * 
	 * @param s
	 * @return
	 */
	public static boolean click(String rid, BanerAd ad, ProxyIp proxyIp, Mobile mobile) {
		boolean ret = false;
		StringBuilder sb = new StringBuilder();
		sb.append("acttype=").append(ad.getActtype()).append("&");//

		JSONObject s = new JSONObject();
		// 根据设备信息,获取广告区域
		int x = Utils.getNum(50, 320);
		int y = Utils.getNum(64, 114);
		s.put("down_x", x);
		s.put("up_x", x);
		s.put("down_y", y);
		s.put("up_y", y);

		sb.append("s=").append(s.toString());
		String url = ad.getRl() + "&" + sb.toString();
		Proxy proxy = Utils.setProxy(proxyIp.getIp(), proxyIp.getPort());
		int code = HttpUtils.getResponeCode(url, proxy, mobile.getUserAgent());
		if (code == 200 || code == 302) {
			ret = true;
		}
		logger.info("rid:{},proxy:{},url:{},code:{},click:{}", rid, proxyIp.toString(), url, code, ret);
		return ret;
	}

}
